package com.bolt.admin.module.sys.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bolt.admin.module.sys.entity.TableConfig;
import com.bolt.admin.module.sys.entity.TableHeadConfig;
import com.bolt.admin.module.sys.entity.UserTableHeadConfig;
import com.bolt.admin.module.sys.entity.UserTableHeadConfigPK;
import com.bolt.admin.module.sys.repository.TableConfigRepository;
import com.bolt.admin.module.sys.repository.TableHeadConfigRepository;
import com.bolt.admin.module.sys.repository.UserTableHeadConfigRepository;
import com.bolt.common.utils.ArrayUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.exception.ServiceException;
import com.bolt.core.view.components.FormItem;
import com.bolt.core.view.components.ListDataLoad;
import com.bolt.support.base.service.BaseService;
import com.bolt.support.spring.jpa.repository.BasicJpaRepository;
import com.bolt.support.spring.jpa.specification.Specifications;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author michao
 */
@Service
@Transactional(readOnly = true,rollbackFor = Exception.class)
public class TableConfigService extends BaseService<TableConfig, String> implements ListDataLoad {
    
    @Autowired
    private TableConfigRepository sysTableConfigRepository;

    @Autowired
    private TableHeadConfigRepository sysTableHeadConfigRepository;

    @Autowired
    private UserTableHeadConfigRepository userHeadConfigRepository;
    

    @Override
    protected BasicJpaRepository<TableConfig, String> getRepository() {
        return sysTableConfigRepository;
    }
    
    
    @SuppressWarnings("unchecked")
    @Override
	protected void preInsert(TableConfig entity) {
		long count = sysTableConfigRepository.count(Specifications.get("tableId",entity.getTableId()));
		if (count > 0) {
			throw new ServiceException("表ID已经存在,请重新输入!");
		}
	}

    @Override
    @CacheEvict(value = "tableConfigCache", allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public TableConfig save(TableConfig entity) {
		return super.save(entity);
	}

	@Override
	protected void preUpdate(TableConfig tableConfig) {
		TableConfig entity = sysTableConfigRepository.getOne(tableConfig.getId());
		if (tableConfig.getTableHeads() == null) {
			for (TableHeadConfig head : entity.getTableHeads()) {
                head.setTableId(tableConfig.getTableId());
			}
		}
		tableConfig.setTableHeads(entity.getTableHeads());
		if (!tableConfig.getTableId().equals(entity.getTableId())) {
			sysTableHeadConfigRepository.saveAll(tableConfig.getTableHeads());
		}

	}
    
    /**
	 * 将列表配置表头信息转为easyUI DbGrid head 信息
	 */
    public JSONArray getTableHead(String viewHeads,String tableId,String[] defaultHead) {
		TableConfig tableconfig = this.findOne(k->k.eq("tableId", tableId).build()).get();
		List<TableHeadConfig> heads = tableconfig.getTableHeads();
		Collections.sort(heads);
		String[] viewHead = (String[]) ArrayUtil.addAll(viewHeads.split(","),defaultHead);
		JSONArray rowData = new JSONArray();
		for(TableHeadConfig headconfig :heads){
			if(ArrayUtil.indexOf(viewHead,headconfig.getField())!=-1){
				JSONObject data = new JSONObject();
				data.put("field", headconfig.getField());
				data.put("title",headconfig.getTitle());
				data.put("align", "center");
				data.put("width", headconfig.getWidth());
				if(headconfig.getHidden()){
					data.put("hidden", true);	
				}
				rowData.add(data);
			}
		}
		return rowData;
	}

   


	/***
	 * 保存用户列表表关配置
	 */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserTableHeadConfig(String userId,String tableId,String showHead){
         UserTableHeadConfigPK pk = new UserTableHeadConfigPK(userId,tableId);
         UserTableHeadConfig userTableHead = new UserTableHeadConfig();
         userTableHead.setId(pk);
         userTableHead.setShowHead(showHead);
         this.userHeadConfigRepository.save(userTableHead);
	 }
	 
	/**
	 * 根据系统列表配置与用户列表配置取出相应列表配置信息
	 * @param userId 当前用户
	 * @param tableId 列表ID
	 * @return
	 */
    @Cacheable(value="tableConfigCache", key="#tableId")
	public TableConfig findTableConfig(String userId, String tableId) {

        TableConfig tableconfig = this.findOne(k->k.eq("tableId", tableId).build()).get();
        tableconfig.getTableHeads();
        UserTableHeadConfigPK pk = new UserTableHeadConfigPK(userId,tableId);
        Optional<UserTableHeadConfig> userTableHead = userHeadConfigRepository.findById(pk);
        if(userTableHead.isPresent()){
            return tableconfig;
        }
        userTableHead.ifPresent(one ->{
            String[] showHead = StrUtil.split(one.getShowHead(), ",");
            if (ArrayUtil.isNotEmpty(showHead)) {
                List<TableHeadConfig> heads = tableconfig.getTableHeads();
                for (TableHeadConfig head : heads) {
                    if (ArrayUtil.contains(showHead, head.getField())) {
                        head.setHidden(false);
                    }
                }
            }
        });
        return tableconfig;
	}

    /**
     * 用于前台下拉列表数据显示
     */
    @Override
    public Map <String, String> load(FormItem formItem, Map  map) {
        // TODO Auto-generated method stub
        List<TableConfig> confings = sysTableConfigRepository.findDistinctTableConfig();
        Map<String,String> r = new LinkedHashMap<String,String>();
        for(TableConfig config : confings){
            r.put(config.getTableId(), config.getTableTitle());
        }
        return r;
    }
}
